import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import { mediaRoutes } from './routes/media';
import { cloudRoutes } from './routes/cloud';

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(helmet());
app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:3000'],
  credentials: true
}));
app.use(morgan('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 路由
app.use('/api/media', mediaRoutes);
app.use('/api/cloud', cloudRoutes);

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 错误处理
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 Server running on http://localhost:${PORT}`);
  console.log('📺 ShadowStream Player Backend Started');
  console.log('🔧 Available endpoints:');
  console.log('   - GET  /api/media/parse');
  console.log('   - GET  /api/media/info');
  console.log('   - GET  /api/media/qualities');
  console.log('   - GET  /api/cloud/list/:provider');
  console.log('   - GET  /api/cloud/download/:provider');
  console.log('   - GET  /api/cloud/search/:provider');
});
